﻿using Aliyun.OSS;
using Md.Api.DDD;
using Md.Api.Model.Util.Oss.Request;
using Md.Api.Model.Util.Oss.Response;

namespace Md.Util.Service.Oss;
/// <summary>
/// 阿里云OSS文件下载服务
/// 相关文档：https://help.aliyun.com/zh/oss/developer-reference/streaming-download-3?spm=a2c4g.11186623.0.0.59fe1290PZDhex
/// </summary>
public class AliOSSDownloadService : ApiBase<RequestAliOSSDownloadModel>
{
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(Parameter.YunFileName))
        {
            throw new AggregateException("云文件名称不能为空");
        }

        var endpoint = JsonConfig.JsonRead("MdAli:OSSAdvMdStorage:Endpoint");
        var accessKeyId = JsonConfig.JsonRead("MdAli:AccessKeyId");
        var accessKeySecret = JsonConfig.JsonRead("MdAli:AccessSecret");
        var bucketName = JsonConfig.JsonRead("MdAli:OSSAdvMdStorage:BucketName");

        var ext = Parameter.YunFileName.Split(".")[1];
        var localFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
        var localFilePath = $"{FileBasePath}/{localFileName}.{ext}";

        var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

        var request = client.GetObject(bucketName, Parameter.YunFileName);

        using (var requestStream = request.Content)
        {
            using (var fs = File.Open(localFilePath, FileMode.OpenOrCreate))
            {
                int length = 4 * 1024;
                var buf = new byte[length];
                do
                {
                    length = requestStream.Read(buf, 0, length);
                    fs.Write(buf, 0, length);
                } while (length != 0);
            }
        }

        var responseModel = new ResponseAliOSSDownloadModel();
        responseModel.localFilePath = localFilePath;
        responseModel.yunFilePath = Parameter.YunFileName;

        Result.Data = responseModel;
        Result.Msg = "success";
    }
}
